﻿/// Author:					Walter Ferrari
/// Created:				2010-01-18
/// ref:                    http://www.snello.it
/// The use and distribution terms for this software are covered by the 
/// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)  
/// By using this software in any fashion, you are agreeing to be bound by 
/// the terms of this license.
///
/// You must not remove this notice, or any other, from this software.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using InteractChartCommonLib;
using System.Collections;
using System.Windows.Data;
using XLSXparsingLib;

namespace DataFilesViewer.Controls
{
    [TemplatePart(Name = dfvDatagrid.ElementMainGridName, Type = typeof(DataGrid))]
    [TemplatePart(Name = dfvDatagrid.ElementMainGridDragDropName, Type = typeof(DataGridDragDropTarget))]
    public class dfvDatagrid : Control, IdfvControl
    {
        internal DataGrid _elementMainGrid;
        internal const string ElementMainGridName = "MainGridElement";

        internal IFileDropFormat _fileDropped;
        internal string _itemSelected;



        internal DataGridDragDropTarget _elementMainGridDragDrop;
        internal const string ElementMainGridDragDropName = "MainGridDragDropElement";

        public event EventHandler TemplateApplied; 

        public dfvDatagrid()
        {
            this.DefaultStyleKey = typeof(dfvDatagrid);
        }

        /// <summary>
        /// Gets or sets the main mainGrid element.
        /// </summary>
        /// <value>The main chart element.</value>
        private DataGrid MainGridElement
        {
            get { return _elementMainGrid; }
            set { _elementMainGrid = value; }
        }

        /// <summary>
        /// Gets or sets the main GridDragDrop element.
        /// </summary>
        /// <value>The main GridDragDrop element.</value>
        private DataGridDragDropTarget MainGridDragDropElement
        {
            get { return _elementMainGridDragDrop; }
            set { _elementMainGridDragDrop = value; }
        }


        private IFileDropFormat FileDropped
        {
            get { return _fileDropped; }
            set { _fileDropped = value; }
        }

        private string ItemSelected
        {
            get { return _itemSelected; }
            set { _itemSelected = value; }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            object mainGridObj = GetTemplateChild(ElementMainGridName);
            Debug.Assert(typeof(DataGrid).IsInstanceOfType(mainGridObj) || (mainGridObj == null),
                "The template part ElementMainGridName is not an instance of DataGrid!");
            MainGridElement = mainGridObj as DataGrid;

            MainGridElement.SelectionMode = DataGridSelectionMode.Extended;

            MainGridElement.SelectionChanged += MainGrid_selectionChanged;
            MainGridElement.MouseLeftButtonDown += MaingGrid_mouseLeftButtonDown;
            MainGridElement.DragEnter += doDragEnter;
            //MainGridElement.DragLeave += doDragLeave;
            MainGridElement.Drop += doDrop;

            object mainGridDragDropObj = GetTemplateChild(ElementMainGridDragDropName);
            Debug.Assert(typeof(DataGridDragDropTarget).IsInstanceOfType(mainGridDragDropObj) || (mainGridDragDropObj == null),
                "The template part ElementMainGridName is not an instance of DataGrid!");
            MainGridDragDropElement = mainGridDragDropObj as DataGridDragDropTarget;
                        
            MainGridDragDropElement.DragLeave += doDragLeave;

            MainGridDragDropElement.Width = this.Width;
            MainGridDragDropElement.Background = new SolidColorBrush(Colors.Red);
            MainGridElement.Width = this.Width;
            TemplateApplied(this, null);
        }

        private void MainGrid_selectionChanged(object sender, SelectionChangedEventArgs e)
        {
            IList list = MainGridElement.SelectedItems;
            // col = MainGridElement.CurrentColumn.DisplayIndex -> gives the index of the cell column
            // row = MainGridElement.SelectedIndex -> the index of the row
           // MainGridElement.SelectedItems;
        }

        private void MaingGrid_mouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
        }

        private void doDragEnter(object sender, DragEventArgs e)
        {
        }

        private void doDragLeave(object sender, Microsoft.Windows.DragEventArgs e)
        {

        }

        private void doDrop(object sender, DragEventArgs e)
        {
            
            if (e.Data == null)
                return;
        }

        public void UpdateMainGrid()
        {
            if (MainGridElement == null)
                return;

            IEnumerable<IDictionary> datasource = FileDropped.GetData(ItemSelected);

            MainGridElement.Columns.Clear();

            if (datasource.Count() == 0)
            {
                MainGridElement.Columns.Add(
                    new DataGridTextColumn
                    {
                        Header = "There are no items!",
                        Binding = new Binding("")
                    });
                MainGridElement.ItemsSource = "";

                return;
            }

            // create columns
            IDictionary firstRow = null;

            try{
                firstRow = datasource.First();
            }
            catch{
                return;
            }

            foreach (DictionaryEntry pair in firstRow)
            {
                MainGridElement.Columns.Add(
                    new DataGridTextColumn
                    {
                        Header = pair.Value,
                        Binding = new Binding(pair.Key.ToString())
                    });
            }
            // we assume that the first column contains the headers of the columns
            MainGridElement.ItemsSource = datasource.Skip(1).ToDataSource();
        }

        public void AttachDatasource(IFileDropFormat fileDropped, string itemSelected)
        {
            FileDropped = fileDropped;
            ItemSelected = itemSelected;
        }
    }
}

